<template>
  <el-card>
    <h2 class="mb-4">课题申请记录</h2>

    <el-select
      v-model="topicId"
      placeholder="选择课题"
      @change="fetchApplications"
      class="mb-4"
      clearable
    >
      <el-option
        v-for="topic in topicOptions"
        :key="topic.id"
        :label="topic.title"
        :value="topic.id"
      ></el-option>
    </el-select>

    <el-table v-loading="loading" :data="applicationList" border style="width: 100%">
      <el-table-column prop="applicant_id" label="申请人ID" width="120"></el-table-column>
      <el-table-column prop="status" label="状态" :formatter="formatStatus" width="120"></el-table-column>
      <el-table-column prop="created_at" label="申请时间" width="180"></el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button size="small" @click="viewApplicationDetail(scope.row)">查看详情</el-button>
          <el-button
            size="small"
            type="success"
            @click="handleApprove(scope.row.id)"
            v-if="scope.row.status === 'pending'"
          >
            同意
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleReject(scope.row.id)"
            v-if="scope.row.status === 'pending'"
          >
            拒绝
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="mt-4"
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.size"
      :total="pagination.total"
      @current-change="handlePageChange"
      layout="prev, pager, next, jumper"
    />

    <!-- 申请详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="申请详情" width="60%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="申请ID">{{ currentApplication.id }}</el-descriptions-item>
        <el-descriptions-item label="申请人ID">{{ currentApplication.applicant_id }}</el-descriptions-item>
        <el-descriptions-item label="课题ID">{{ currentApplication.project_id }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ formatStatus(currentApplication) }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ formatDate(currentApplication.created_at) }}</el-descriptions-item>
        <el-descriptions-item label="求职信">
          <pre class="whitespace-pre-wrap">{{ currentApplication.cover_letter }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="简历">
          <a v-if="currentApplication.resume" :href="currentApplication.resume" target="_blank" class="text-blue-500">查看简历</a>
          <span v-else class="text-gray-400">无</span>
        </el-descriptions-item>
        <el-descriptions-item label="作品集">
          <a v-if="currentApplication.portfolio" :href="currentApplication.portfolio" target="_blank" class="text-blue-500">查看作品集</a>
          <span v-else class="text-gray-400">无</span>
        </el-descriptions-item>
        <el-descriptions-item label="反馈" v-if="currentApplication.feedback">
          {{ currentApplication.feedback }}
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { Application, Topic } from '@/api/topic';
import { getMyProjects, getApplications, updateApplicationStatus } from '@/api/topic';

const route = useRoute();

// 分页参数
const pagination = ref({
  page: 1,
  size: 10,
  total: 0
});

// 数据
const topicOptions = ref<Topic[]>([]);
const applicationList = ref<Application[]>([]);
const loading = ref(false);
const topicId = ref<number | null>(route.query.topicId ? Number(route.query.topicId) : null);

// 申请详情
const detailDialogVisible = ref(false);
const currentApplication = ref<Application>({
  id: 0,
  project_id: 0,
  applicant_id: 0,
  status: 'pending',
  cover_letter: '',
  resume: '',
  portfolio: '',
  created_at: '',
  updated_at: ''
});

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString();
};

// 状态格式化
const formatStatus = (row: Application) => {
  const statusMap: Record<string, string> = {
    pending: '待审核',
    approved: '已同意',
    rejected: '已拒绝',
    confirmed: '已确认'
  };
  return statusMap[row.status] || row.status;
};

// 获取企业课题（用于下拉选择）
const fetchTopics = async () => {
  try {
    loading.value = true;
    const res = await getMyProjects();
    topicOptions.value = res.data.data.filter((item: Topic) => item.status !== 'draft');
  } catch (error) {
    ElMessage.error('获取课题列表失败');
  } finally {
    loading.value = false;
  }
};

// 获取申请记录
const fetchApplications = async () => {
  if (!topicId.value) {
    applicationList.value = [];
    return;
  }

  loading.value = true;
  try {
    const params = {
      project_id: topicId.value,
      page: pagination.value.page,
      size: pagination.value.size
    };
    const res = await getApplications(params);
    applicationList.value = res.data.data;
    pagination.value.total = res.data.total || 0;
  } catch (error) {
    ElMessage.error('获取申请记录失败');
  } finally {
    loading.value = false;
  }
};

// 分页变化
const handlePageChange = () => {
  fetchApplications();
};

// 查看申请详情
const viewApplicationDetail = (row: Application) => {
  currentApplication.value = { ...row };
  detailDialogVisible.value = true;
};

// 处理申请状态更新
const updateApplication = async (id: number, status: 'approved' | 'rejected') => {
  try {
    await ElMessageBox.confirm(
      `确定要${status === 'approved' ? '同意' : '拒绝'}该申请吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    await updateApplicationStatus(id, { status });
    ElMessage.success(`操作成功，申请已${status === 'approved' ? '同意' : '拒绝'}`);
    fetchApplications();
    detailDialogVisible.value = false;
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败');
    }
  }
};

// 同意申请
const handleApprove = async (id: number) => {
  await updateApplication(id, 'approved');
};

// 拒绝申请
const handleReject = async (id: number) => {
  await updateApplication(id, 'rejected');
};

onMounted(() => {
  fetchTopics();
  if (topicId.value) {
    fetchApplications();
  }
});
</script>

<style scoped>
.whitespace-pre-wrap {
  white-space: pre-wrap;
  font-family: inherit;
  margin: 0;
  padding: 0;
}

.mb-4 {
  margin-bottom: 1rem;
}

.mt-4 {
  margin-top: 1rem;
}

.text-blue-500 {
  color: #3b82f6;
}

.text-gray-400 {
  color: #9ca3af;
}
</style>
